package com.lp.article.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lp.article.service.ICollectService;
import com.lp.model.config.AppResult;
import com.lp.model.config.CodeMsg;
import com.lp.model.dto.article.CollectDto;
import com.lp.model.dto.article.PageDto;
import com.lp.model.entity.article.Article;
import com.lp.model.entity.article.vo.PageVO;
import com.lp.model.entity.user.User;
import com.lp.model.utils.PageUtils;
import com.lp.model.utils.UserUtils;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/article/collect")
public class CollectController {

    @Autowired
    private ICollectService collectService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 收藏
     * @param request
     * @param collectDto
     * @return
     */
    @PostMapping("/play")
    public AppResult collect(HttpServletRequest request,
                             @RequestBody @NonNull CollectDto collectDto) {
        //1.非空校验
        if(collectDto.getArticleId() == null) {
            return AppResult.fail(CodeMsg.FAIL_NULL_FOLLOW);
        }
        //2.准备数据
        User userByToken = UserUtils.getUserByToken(redisTemplate, objectMapper, request);
        collectService.collect(userByToken.getId(), collectDto);
        return AppResult.success();
    }

    /**
     * 收藏列表
     * @param page 分页数据 + 用户id(谁的收藏列表)
     * @return
     */
    @PostMapping("/page")
    public AppResult collectList(@RequestBody @NonNull PageDto page) {
        //1.非空校验
        if(!PageUtils.checkPageDto(page)) {
            return AppResult.fail(CodeMsg.FAIL_ERROR_ARTICLE_PAGE);
        }
        //2.获取收藏列表
        PageVO<Article> collectList = collectService.getCollectList(page);
        return AppResult.success(collectList);
    }

}
